package slic.solicitudcuenta;

import java.io.IOException;
import java.util.Date;
import java.util.Enumeration;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletRequest;
import javax.portlet.PortletSession;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;

import slic.solicitudcuenta.receptores.ReceptorType;

import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.servlet.SessionMessages;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.StringUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.util.PortalUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;

public class SolicitudCuentaPortlet extends MVCPortlet {

	private static Log _log = LogFactoryUtil.getLog(SolicitudCuentaPortlet.class);
	
	private static String formularioSolicitudJsp = "/html/solicitudcuenta/formularioSolicitud.jsp";
	private static String solicitudEnviadaJsp = "/html/solicitudcuenta/solicitudEnviada.jsp";
	
	public void solicitarCuenta(ActionRequest request, ActionResponse response) throws SystemException, PortalException {

		String nombre = ParamUtil.get(request, "nombre", "");
		String apellido = ParamUtil.get(request, "apellido", "");
		String dni = ParamUtil.get(request, "dni", "");
		String mail = ParamUtil.get(request, "mail", "");
		String cargo = ParamUtil.get(request, "cargo", "");
		Date ahora = new Date();

		if (!captchaIsValid(request)) {
			SessionErrors.add(request, "invalid-captcha");
		}
		
		if (!emailIsValid(mail)) {
			SessionErrors.add(request, "invalid-mail");
		}
		
		if (SessionErrors.isEmpty(request)) {
			SolicitudCuenta solicitudCuenta = new SolicitudCuenta(nombre, apellido, dni, mail, cargo, ahora);
			for (ReceptorType receptor: Configuracion.obtenerReceptores()) {
				solicitudCuenta.agregarReceptor(receptor);				
			}
			solicitudCuenta.enviar();
			SessionMessages.add(request, "solicitud-enviada");
			response.setRenderParameter("jspPage", solicitudEnviadaJsp);
		} else {
			PortalUtil.copyRequestParameters(request, response);
			response.setRenderParameter("jspPage", formularioSolicitudJsp);			
		}			
		
	}
	
    @Override
    public void serveResource(ResourceRequest resourceRequest,
                             ResourceResponse resourceResponse) throws IOException, PortletException {
        try {
            com.liferay.portal.kernel.captcha.CaptchaUtil.serveImage(resourceRequest, resourceResponse);
        } catch (Exception e) {
            _log.error(e);
        }
    }
    
    private Boolean captchaIsValid(PortletRequest request) {
        String enteredCaptchaText = ParamUtil.getString(request, "captchaText");

        PortletSession session = request.getPortletSession();
        String captchaText = getCaptchaValueFromSession(session);
        if (Validator.isNull(captchaText)) {
            _log.error("Internal Error! Captcha text not found in session");
        	return false;
        }
        return captchaText.equals(enteredCaptchaText);
    }

    private String getCaptchaValueFromSession(PortletSession session) {
        Enumeration<String> atNames = session.getAttributeNames();
        while (atNames.hasMoreElements()) {
            String name = atNames.nextElement();
            if (name.contains("CAPTCHA_TEXT")) {
                return (String) session.getAttribute(name);
            }
        }
        return null;
    }
    
    private Boolean emailIsValid(String mail) {
    	return StringUtil.count(mail, "@") == 1;
    }
	
}
